<!DOCTYPE html>
<html>
<head>
    <title>环境监控系统</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}?v=1.1">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <style>
        /* 基础样式保持不变 */
        .loading {
        color: #666;
        padding: 10px;
        font-style:
        italic;
        }
        .error {
        color: red;
        padding: 10px;
        }
        #dataTable {
        border-collapse: collapse;
        width: 100%;
        }
        #dataTable th, #dataTable td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
        }

        /* 新增图表样式 */
        .chart-container {
            margin: 20px 0;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .chart-title {
            margin-bottom: 15px;
            color: #333;
            font-size: 18px;
        }
        .chart-wrapper {
            width: 100%;
            height: 400px;
        }
    </style>
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
</head>
<body>
    <h1>仓库环境监控</h1>

    <!-- 实时数据模块 -->
    <div id="realtime">
        <h2>当前状态</h2>
        <p>温度：<span id="currentTemp">--</span>℃</p>
        <p>湿度：<span id="currentHum">--</span>%</p>
        <p>更新时间：<span id="updateTime">--</span></p>
    </div>

    <!-- 数据控制模块 -->
    <div class="controls">
        <button onclick="loadData()">刷新数据</button>
        <label>显示最近
            <input type="number" id="rowLimit" min="1" max="50" value="10"> 条记录
        </label>
        <button onclick="loadAllStats()">刷新全部图表</button>
    </div>

    <!-- 历史数据表格 -->
    <div id="dataContainer">
        <div class="loading" id="loading">数据加载中...</div>
        <div class="error" id="error" style="display: none;"></div>
        <table id="dataTable">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>温度(℃)</th>
                    <th>湿度(%)</th>
                </tr>
            </thead>
            <tbody id="dataBody"></tbody>
        </table>
    </div>

    <!-- 小时级统计新布局 -->
    <div class="chart-container">
        <div class="chart-title">小时级统计
           <button onclick="loadHourlyStats()" style="float: right;">刷新</button>
        </div>
        <table id="hourlyStatsTable">
          <thead>
             <tr>
                <th>时间(h)</th>
                <th>温度(℃)</th>
                <th>湿度(%)</th>
             </tr>
           </thead>
           <tbody id="hourlyStatsBody"></tbody>
        </table>
    </div>

    <!-- 统计图表模块 -->
    <div id="stats">
        <div class="chart-container">
            <div class="chart-title">24小时温度/湿度趋势</div>
            <div id="chart24h" class="chart-wrapper"></div>
        </div>

        <div class="chart-container">
            <div class="chart-title">7天温度/湿度趋势</div>
            <div id="chart7d" class="chart-wrapper"></div>
        </div>
    </div>

    <script>
        // 初始化图表实例
        let chart24h, chart7d;
        function initCharts() {
            chart24h = echarts.init(document.getElementById('chart24h'));
            chart7d = echarts.init(document.getElementById('chart7d'));
        }

        // 统一图表配置
        const baseChartOption = {
            tooltip: { trigger: 'axis' },
            legend: { data: ['温度', '湿度'] },
            xAxis: { type: 'category' },
            yAxis: [
                { type: 'value', name: '温度(℃)' },
                { type: 'value', name: '湿度(%)' }
            ],
            series: [
                { name: '温度', type: 'line', yAxisIndex: 0 },
                { name: '湿度', type: 'line', yAxisIndex: 1 }
            ]
        };

        async function loadAllStats() {
            try {
                const [res24h, res7d] = await Promise.all([
                    fetch('/api/stats/24h_trend'),
                    fetch('/api/stats/7d_trend')
                ]);

                // 处理24小时数据
                const data24h = await res24h.json();
                chart24h.setOption({
                    ...baseChartOption,
                    xAxis: { data: data24h.map(d => d.hour) },
                    series: [
                        { ...baseChartOption.series[0], data: data24h.map(d => d.temperature) },
                        { ...baseChartOption.series[1], data: data24h.map(d => d.humidity) }
                    ]
                });

                // 处理7天数据
                const data7d = await res7d.json();
                chart7d.setOption({
                    ...baseChartOption,
                    xAxis: { data: data7d.map(d => d.date) },
                    series: [
                        { ...baseChartOption.series[0], data: data7d.map(d => d.temperature) },
                        { ...baseChartOption.series[1], data: data7d.map(d => d.humidity) }
                    ]
                });
            } catch (err) {
                console.error('图表加载失败:', err);
            }
        }

        // 原数据加载函数保持不变
        // 增强版数据加载函数
        async function loadData() {
            const limit = document.getElementById('rowLimit').value;
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const dataBody = document.getElementById('dataBody');

            loading.style.display = 'block';
            error.style.display = 'none';
            dataBody.innerHTML = ''; // 清空表格

            try {
                // 获取历史数据
                const historyRes = await fetch(`/api/history?limit=${limit}`);
                if (!historyRes.ok) throw new Error('请求失败');
                const historyData = await historyRes.json();

                // 更新历史数据表格
                historyData.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.timestamp}</td>
                        <td>${item.temperature.toFixed(1)}</td>
                        <td>${item.humidity.toFixed(1)}</td>
                    `;
                    dataBody.appendChild(row);
                });

                // 获取最新数据
                const latestRes = await fetch('/api/latest');
                if (!latestRes.ok) throw new Error('请求失败');
                const latestData = await latestRes.json();

                // 更新实时数据
                updateRealtime(latestData);

            } catch (err) {
                error.textContent = `数据加载失败：${err.message || '未知错误'}`;
                error.style.display = 'block';
            } finally {
                loading.style.display = 'none';
            }
        }

        // 实时数据更新函数
        function updateRealtime(data) {
            if (data.error) { // 处理接口错误
                document.getElementById('currentTemp').textContent = '--';
                document.getElementById('currentHum').textContent = '--';
                document.getElementById('updateTime').textContent = '更新失败';
                return;
            }
            document.getElementById('currentTemp').textContent = data.temperature.toFixed(1);
            document.getElementById('currentHum').textContent = data.humidity.toFixed(1);
            document.getElementById('updateTime').textContent = data.timestamp;
        }

        // 新增小时级统计加载函数
        async function loadHourlyStats() {
         try {
            const [hourlyRes, res24h, res7d] = await Promise.all([
                fetch('/api/stats/hourly'),
                fetch('/api/stats/24h_trend'),
                fetch('/api/stats/7d_trend')
            ]);

         // 更新小时统计表格
            const hourlyData = await hourlyRes.json();
            const tableBody = document.getElementById('hourlyStatsBody');
            tableBody.innerHTML = '';
            hourlyData.forEach(item => {
                  const row = document.createElement('tr');
                  row.innerHTML = `
                        <td>${item.hour}</td>
                        <td>${item.avg_temperature.toFixed(1)}</td>
                        <td>${item.avg_humidity.toFixed(1)}</td>
                   `;
                   tableBody.appendChild(row);
            });

            // 更新24小时趋势图
            const data24h = await res24h.json();
            chart24h.setOption({
                ...baseChartOption,
                xAxis: { data: data24h.map(d => d.hour) },
                series: [
                    { ...baseChartOption.series[0], data: data24h.map(d => d.temperature) },
                    { ...baseChartOption.series[1], data: data24h.map(d => d.humidity) }
                ]
            });

            // 更新7天趋势图
            const data7d = await res7d.json();
            chart7d.setOption({
                ...baseChartOption,
                xAxis: { data: data7d.map(d => d.date) },
                series: [
                    { ...baseChartOption.series[0], data: data7d.map(d => d.temperature) },
                    { ...baseChartOption.series[1], data: data7d.map(d => d.humidity) }
                ]
            });

        } catch (err) {
            console.error('统计加载失败:', err);
            document.getElementById('error').textContent = `统计加载失败: ${err.message}`;
            document.getElementById('error').style.display = 'block';
        }
    }

    // 修改初始化函数自动加载小时统计
    window.onload = () => {
        initCharts();
        loadData();
        loadHourlyStats(); // 新增初始化加载
        setInterval(() => { // 定时刷新
            loadData();
            loadHourlyStats();
        }, 10000);// 10 秒间隔
    };
    </script>
   <script src="{{ url_for('static', filename='app.js') }}?v=2.4"></script>
</body>
</html>
